package com.example.validator.constraintvalidators;

import com.example.validator.constraints.FileCount;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 检查上传的文件的数量在 min 到 max 之间
 * @author LeXin Huang
 * @date 2021年03月26日 21:52
 */
public class FileCountValidator implements ConstraintValidator<FileCount, MultipartFile[]> {

    private int min;

    private int max;

    @Override
    public void initialize(FileCount constraintAnnotation) {
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(MultipartFile[] value, ConstraintValidatorContext context) {
        if (null == value) {
            return 0 == min;
        }
        return value.length >= min && value.length <= max;
    }
}
